package com.community.controller;

import com.community.pojo.entity.Result;
import com.community.service.impl.AliyunOssService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
public class UploadController {
    private final AliyunOssService ossService;

    @PostMapping("/image")
    public Result uploadImage(
            @RequestParam("file") MultipartFile file,
            HttpServletRequest request) {

        log.info("图片上传请求，操作人token: {}", request.getHeader("token"));

        try {
            // 文件校验
            if (file.isEmpty()) {
                return Result.buildFail(1,"请选择要上传的文件");
            }
            if (!Objects.requireNonNull(file.getContentType()).startsWith("image/")) {
                return Result.buildFail(1,"只允许上传图片文件");
            }
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.buildFail(1,"图片大小不能超过5MB");
            }

            // 上传到OSS
            String fileUrl = ossService.upload(file);

            return Result.buildSuccess(fileUrl);

        } catch (Exception e) {
            log.error("图片上传失败", e);
            return Result.buildFail(1,e.getMessage());
        }
    }
}